/**
 * Mock数据统一入口 - TypeScript版本
 * 统一管理所有Mock接口和数据
 */

import Mock from 'mockjs'

// 确保Mock对象可用
if (!Mock) {
  console.error('[MOCK] Mock.js 未正确导入')
}
import { setupCustomerMock } from './customer'
import { setupOperationLogsMock } from './operation-logs'
import { setupProductMock } from './product'
import logger from '@/utils/logger'

// Mock配置
const MOCK_CONFIG = {
  timeout: '200-600', // 模拟网络延迟
  enable: import.meta.env.VITE_MOCK_ENABLE === 'true'
}

/**
 * 设置Mock服务
 */
export const setupMock = (): void => {
  console.log('[MOCK] 检查Mock配置:', MOCK_CONFIG)
  
  if (!MOCK_CONFIG.enable) {
    logger.info('[MOCK] Mock数据服务已禁用')
    return
  }
  
  logger.info('[MOCK] Mock数据服务启动中...')
  console.log('[MOCK] Mock对象:', Mock)

  // 配置Mock
  Mock.setup({
    timeout: MOCK_CONFIG.timeout
  })

  try {
    // 注册各模块Mock接口
    setupBasicMockRoutes()
    setupCustomerMock()
    setupOperationLogsMock()
    setupProductMock()
    
    logger.info('[MOCK] Mock数据服务启动完成')
    logger.info('[MOCK] 已注册模块:', Object.keys(availableModules).filter(k => availableModules[k]))
    console.log('[MOCK] Mock._mocked:', Mock._mocked)
    console.log('[MOCK] 已注册的Mock路由数量:', Object.keys(Mock._mocked).length)
    console.log('[MOCK] 注册的路由列表:', Object.keys(Mock._mocked))
    
    // 验证createResponse函数
    const testResponse = createResponse('test', '测试成功')
    console.log('[MOCK] createResponse测试:', testResponse)
  } catch (error) {
    logger.error('[MOCK] Mock服务启动失败:', error)
    console.error('[MOCK] 详细错误:', error)
    throw error
  }
}

/**
 * 设置基础Mock接口
 */
const setupBasicMockRoutes = (): void => {
  // 系统健康检查
  Mock.mock('/api/health', 'get', () => {
    return createResponse({
      status: 'ok',
      timestamp: new Date().toISOString(),
      modules: availableModules,
      message: 'Mock服务运行正常'
    }, 'Mock服务健康')
  })

  // 数据字典接口
  Mock.mock('/api/dictionary', 'get', () => {
    return createResponse(mockDictionaries, '获取数据字典成功')
  })

  Mock.mock(/\/api\/dictionary\/([^\/]+)$/, 'get', (options) => {
    const key = options.url.split('/').pop()
    const dictionary = mockDictionaries[key]
    
    if (dictionary) {
      return createResponse(dictionary, `获取${key}字典成功`)
    } else {
      return createResponse(null, '字典项不存在', 404)
    }
  })
}

/**
 * 可用模块状态
 */
const availableModules: Record<string, boolean> = {
  dictionary: true,     // ✅ 数据字典
  customers: true,      // ✅ 客户管理
  operationLogs: true,  // ✅ 操作日志
  products: true,       // ✅ 产品管理数据
  // dashboard: false,    // 仪表板数据
  // sales: false,        // 销售机会数据
  // activities: false,   // 邀约活动数据
  // tours: false,        // 出团管理数据
  // aftercare: false,    // 售后服务数据
  // system: false        // 系统管理数据
}

/**
 * 基础数据字典
 */
const mockDictionaries: Record<string, any> = {
  customerStatus: [
    { label: '有效客户', value: '有效客户', color: '#34C759' },
    { label: '潜在客户', value: '潜在客户', color: '#5AC8FA' },
    { label: '无效客户', value: '无效客户', color: '#8E8E93' },
    { label: '已成交客户', value: '已成交客户', color: '#FF9500' },
    { label: '黑名单', value: '黑名单', color: '#FF3B30' }
  ],
  healthStatus: [
    { label: '健康良好', value: '健康良好', color: '#34C759' },
    { label: '健康一般', value: '健康一般', color: '#FFCC00' },
    { label: '健康较差', value: '健康较差', color: '#FF9500' },
    { label: '健康很差', value: '健康很差', color: '#FF3B30' }
  ],
  genders: [
    { label: '男', value: '男' },
    { label: '女', value: '女' }
  ]
}

/**
 * 创建标准响应格式
 */
export const createResponse = <T = any>(
  data: T, 
  message: string = 'success', 
  code: number = 200
): MockResponse<T> => {
  return {
    code,
    message,
    data,
    timestamp: new Date().toISOString(), // 修复：使用ISO字符串格式
    success: code === 200
  }
}

/**
 * 创建分页响应格式
 */
export const createPageResponse = <T = any>(
  data: T[], 
  total: number, 
  page: number = 1, 
  size: number = 20
): MockResponse<PageResult<T>> => {
  return createResponse({
    list: data,
    pagination: {
      current: page,
      pageSize: size,
      total: total,
      pages: Math.ceil(total / size),
      hasNext: page * size < total,
      hasPrevious: page > 1
    }
  })
}

/**
 * Mock响应接口 - 匹配ApiResponse格式
 */
export interface MockResponse<T = any> {
  code: number
  message: string
  data: T
  timestamp: string  // 修复：使用字符串格式匹配ApiResponse
  success: boolean
}

/**
 * 分页结果接口
 */
export interface PageResult<T = any> {
  list: T[]
  pagination: {
    current: number
    pageSize: number
    total: number
    pages: number
    hasNext: boolean
    hasPrevious: boolean
  }
}

/**
 * 模块加载检查
 */
export const loadModule = (moduleName: string): boolean => {
  if (availableModules[moduleName]) {
    logger.info(`[MOCK] 模块 ${moduleName} 已加载`)
    return true
  } else {
    logger.warn(`[MOCK] 模块 ${moduleName} 尚未创建`)
    return false
  }
}

// 导出配置和工具
export {
  MOCK_CONFIG,
  availableModules,
  mockDictionaries
}

export default setupMock